<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ include file="../../include/tag.jsp" %>
<style type="text/css">
    .sku-container .layui-form-select {
        width: 93%;
    }

    .sku-container .layui-form-select dl {
        padding: 0px;
    }

    .sku-container .layui-select-title {
        display: none!important;
    }

    .sku-container .top83 {
        top: -83px!important;
    }

    .t-verify-red {
        font-size: 16px;
        margin-right: 5px;
        color: #e94e20;
        vertical-align: middle;
    }

    .border-0 {
        /*border-width: 0px;*/
        /*padding-left: 0px;*/
    }

    .w-70px {
        width: 70px;
    }

    .w-90px {
        width: 90px;
    }

    .w-50px {
        width: 50px;
    }

    .rc-sku-group .layui-word-aux {
        padding: 0px !important;
    }
</style>
<div class="layui-form-item">
    <label class="layui-form-label">商品规格</label>
    <div class="layui-input-block">
        <button class="layui-btn layui-btn-danger addBtn" type="button"><i class="iconfont icon-add btn-icon"></i> 添加规格</button>
        <div class="sku-container spec-selected-list mt20"></div>
        <div id="hiddenForm"></div>
    </div>
</div>
<div class="layui-form-item ${hasSpec ? '' : 'dn'}">
    <label class="layui-form-label">规格明细</label>
    <div class="layui-input-block">
        <table class="layui-table" id="myTable" lay-size="sm"></table>
    </div>
</div>
<!-- 规格名 -->
<script type="text/html" id="sku_template">
    {{# var newIndex = -1; }}
    {{# var hasSpec = false; }}
    {{# layui.each(d, function(index, spec){ }}
    {{# newIndex++; }}
    <div class="rc-sku-group" data-model="{{ spec.id }}">
        <div class="group-title">
            <label class="layui-form-label">规格名：</label>
            <div class="layui-input-inline spec-case">
                <input type="text" class="layui-input spec-name" value="{{ spec.name }}" readonly/>
            </div>
            {{# if(newIndex == 0){ }}
            {{# if(spec.specPicFlag == 1){ }}
            {{# hasSpec = true; }}
            {{# } }}
            <div class="layui-form-mid layui-word-aux">
                <div class="layui-input-inline">
                    <input type="checkbox" lay-skin="primary" class="add-sub-item-pic" lay-filter="picChk"
                           {{=hasSpec ? 'checked' : ''}} title="添加规格图片"/>
                </div>
            </div>
            {{# } }}
            <div class="layui-form-mid layui-word-aux" style="float: right">
                <span class="group-opt icon-close-new" style="top: 0px;"></span>
            </div>
        </div>
        <div class="group-container">
            <label class="layui-form-label">规格值：</label>
            <div class="event-create-sign-select">
                {{# layui.each(spec.subModelId, function(subIndex, id){ }}
                <div class="sub-item" data-id="{{ id }}" data-new-id="{{ id }}">
                    <div class="layui-input-inline sub-item-text">
                        <input type="text" class="layui-input" value="{{ spec.subModelName[subIndex] }}"/>
                    </div>
                    <span class="sub-item-opt icon-close-new"></span>
                    <select class="layui-select url-opt" lay-filter="specValue-select"></select>
                    {{# if(newIndex == 0 && hasSpec){ }}
                    <div class="upload-img-wrap">
                        <input type="hidden" name="pic" lay-verify="pic" value="{{ spec.subModelPic[subIndex] }}">
                        {{# if(util.isValid(spec.subModelPic[subIndex])){ }}
                            <img src="{{ spec.subModelPic[subIndex] }}" class="cover-img"/>
                            <div class="upload-icon upload-icon-update">
                                替换
                            </div>
                        {{# }else{ }}
                            <img src="{{ spec.subModelPic[subIndex] }}" class="cover-img" style="display: none" />
                            <div class="upload-icon">
                                +
                            </div>
                        {{# } }}
                        <span class="sub-item-pic-opt icon-close-new"></span>
                    </div>
                    {{# } }}
                </div>
                {{# }); }}
                <span class="add-sub-item red spec-item-add">添加规格值</span>
                <div class="cl"></div>
            </div>
        </div>
    </div>
    {{# }); }}
</script>
<!-- 添加规格值 -->
<script type="text/html" id="subItem_template">
    <div class="sub-item">
        <div class="layui-input-inline sub-item-text">
            <input type="text" class="layui-input" value=""/>
        </div>
        <span class="sub-item-opt icon-close-new"></span>
        <select class="layui-select url-opt" lay-filter="specValue-select"></select>
        {{# if(d.picChk){ }}
        <div class="upload-img-wrap">
            <input type="hidden" name="pic" lay-verify="pic" value="">
            <img src="" class="cover-img" style="display: none"/>
            <div class="upload-icon">
                +
            </div>
            <span class="sub-item-pic-opt icon-close-new"></span>
        </div>
        {{# } }}
    </div>
</script>
<!-- 上传图片 -->
<script type="text/html" id="subItemPic_template">
    <div class="upload-img-wrap">
        <input type="hidden" name="pic" lay-verify="pic" value="">
        <img src="" class="cover-img" style="display: none"/>
        <div class="upload-icon">
            +
        </div>
        <span class="sub-item-pic-opt icon-close-new"></span>
    </div>
</script>
<!-- 添加规格图片复选框 -->
<script type="text/html" id="picChk_template">
    <div class="layui-form-mid layui-word-aux">
        <div class="layui-input-inline">
            <input type="checkbox" lay-skin="primary" class="add-sub-item-pic" lay-filter="picChk" title="添加规格图片"/>
        </div>
    </div>
</script>
<!-- 批量操作 -->
<script type="text/html" id="batchOpt_template">
    <tr>
        <td colspan="{{ d.rowspanLength }}">
            <span>批量设置：</span>
            <div class="dib mr15">
                <span class='red mr5 setting-price'>价格</span>
                <input type='number' class='layui-input dib spec-all-price w-70px' min='1' />
            </div>
            <div class="dib mr15">
                <span class='red mr5 setting-stock'>库存</span>
                <input type='text' class='layui-input dib spec-all-stock w-70px' />
            </div>
            <div class="dib mr15">
                <span class='red mr5 setting-stock'>成本价</span>
                <input type='number' class='layui-input dib spec-all-cost-price w-70px' min='1' />
            </div>
            <div class="dib mr5">
                <span class='red mr5 setting-stock'>批发价</span>
                <input type='number' class='layui-input dib spec-all-trade-price w-70px' min='1' />
            </div>
            <div class="dib mr5">
                <span class='red mr5 setting-stock'>规格编码</span>
                <input type='text' class='layui-input dib spec-all-number' style="width: 100px" />
            </div>
        </td>
    </tr>
</script>
<script type="text/javascript" src="${ctx}/script/common/util.js"></script>
<script type="text/javascript" charset="UTF-8">
    var specIndex = 30;
    var specModels = {};
    var subPriceStock = {};
    var delModelList = {};
    var laytpl = null, form = null;

    $(function () {
        layui.use(['laytpl', 'form'], function () {
            laytpl = layui.laytpl;
            form = layui.form;
        });

        Array.max = function (array) {
            return Math.max.apply(Math, array);
        };

        Array.min = function (array) {
            return Math.min.apply(Math, array);
        };

        txzSpec = {
            myTpl: null,
            myForm: null,
            hasSpec: false,
            productId: null,
            picChk: false,
            specValue : {},
            specValue2 : {},
            initPlugin : function () {
                var that = this;
                that.myTpl = laytpl;
                that.myForm = form;
            },
            init: function (data) {
                var that = this;
                that.initPlugin();
                if (util.isValid(data)) {
                    var results = JSON.parse(data);
                    that.loadData(results);
                }
                that.addEvent();
                that.buildSkuUpload();
            },
            loadData: function (results) {
                // 加载数据
                var that = this;
                $.each(results.speModels, function (index, model) {
                    specModels[model.id] = model;
                });

                $.each(results.products, function (index, product) {
                    subPriceStock[product.model] = {
                        price: product.price,
                        stock: product.stock,
                        realStock: product.realStock,
                        salesNum: product.salesNum,
                        imgUrl: product.imgUrl,
                        productId: product.productId,
                        costPrice : product.costPrice || '',
                        tradePrice : product.tradePrice || '',
                        number : product.number || ''
                    }
                });
                delModelList = results.delModelList;

                that.hasSpec = results.hasSpec;
                if (!this.hasSpec) {
                    that.productId = results.product.productId;
                }
                that.getLiHtml();
                that.paintSpecificationTable();
            },
            buildTableUpload: function () {
                $('.layui-table tbody tr').on('click', '.sel-single-img', function () {
                    var that = this;
                    var $cover_img = $(that).siblings("img"), $pic = $(that).siblings("[name=prodPic]");
                    txz.openSelImg({
                        min: 1,
                        max: 1,
                        info: '建议尺寸：800x450',
                        type: '<%=TargetType.MALL.getCode()%>',
                        cb: function (imgs) {
                            $(that).removeAttr('disabled');
                            $cover_img.attr('src', imgs[0].path);
                            $pic.val(imgs[0].path);
                        }
                    })
                })
            },
            buildSkuUpload: function () {
                var that = this;
                $(".spec-selected-list").on('click', '.upload-icon', function () {
                    var $this = $(this);
                    var $cover_img = $this.siblings("img"), $pic = $this.siblings("[name=pic]");
                    txz.openSelImg({
                        min: 1,
                        max: 1,
                        info: '建议尺寸：800x450',
                        type: '<%=TargetType.MALL.getCode()%>',
                        cb: function (imgs) {
                            $cover_img.attr('src', imgs[0].path);
                            $pic.val(imgs[0].path);
                            $cover_img.css('display', 'block');
                            $this.addClass("upload-icon-update");
                            $this.text("替换");
                            that.addOrDeleteSubItem($this, true);
                            that.picChk = true;
                        }
                    })
                })
            },
            // 增加或删除规格值
            addOrDeleteSubItem: function (thisObj, isRender) {
                var that = this;
                var $this = thisObj;
                var modelId = $this.closest(".rc-sku-group").attr("data-model");
                var specSort = $this.closest(".rc-sku-group").index() + 1;
                specModels[modelId].subModelName = [];
                specModels[modelId].subModelId = [];
                specModels[modelId].subModelPic = [];
                specModels[modelId].subModelSort = [];
                $this.closest(".event-create-sign-select")
                    .find(".sub-item .sub-item-text").each(function (subIndex, ele) {
                    var subName = $(ele).find("input").val();
                    if (subName == "") {
                        return;
                    }
                    var subId = $(ele).closest(".sub-item").attr("data-new-id") || '';
                    if (!util.isValid(subId)) {
                        subId = Math.floor(Math.random() * (999 - 99 + 1) + 99) + specIndex;
                    }
                    // if (that.picChk) {
                    var pic = $(ele).closest(".sub-item").find("[name=pic]").val();
                    specModels[modelId].subModelPic.push(pic);
                    // }
                    specModels[modelId].subModelName.push(subName);
                    specModels[modelId].subModelId.push(subId);
                    specModels[modelId].subModelSort.push(subIndex + 1);
                    specModels[modelId].sort = specSort;
                });

                var length = $(".sub-item").length;
                var dnLength = $(".sub-item.dn").length;
                if (length - dnLength > 0) {
                    $("#myTable").closest(".layui-form-item").removeClass("dn");
                    $("[name=price]").prop("readonly", true);
                    $("[name=stock]").prop("readonly", true);
                    $("[name=costPrice]").prop("readonly", true);
                    $("[name=tradePrice]").prop("readonly", true);
                    that.hasSpec = true;
                } else {
                    $("#myTable").closest(".layui-form-item").addClass("dn");
                    $("[name=price]").prop("readonly", false);
                    $("[name=stock]").prop("readonly", false);
                    $("[name=costPrice]").prop("readonly", false);
                    $("[name=tradePrice]").prop("readonly", false);
                    that.hasSpec = false;
                }

                if (isRender) {
                    that.paintSpecificationTable();
                }
            },
            updatePrice: function (price) {
                if (util.isValid(price)) {
                    $("[name=price]").val(price);
                } else {
                    var array = new Array();
                    $(".spec-price").each(function (index, ele) {
                        var value = $(ele).val() || 0;
                        if (value > 0) {
                            array.push(value);
                        }
                    });
                    var min = array.length > 0 && Array.min(array) ? Array.min(array) : 0;
                    var max = array.length > 0 && Array.max(array) ? Array.max(array) : 0;
                    if (min == max) {
                        $("[name=price]").val(min);
                    } else {
                        $("[name=price]").val(min + '~' + max);
                    }
                }
            },
            // 计算库存
            updateStock: function () {
                var allStock = 0;
                var allRealStock = 0;
                $(".spec-stock").each(function (index, ele) {
                    var value = $(ele).val() || 0;
                    if (!isNaN(value)) {
                        allStock += parseInt(value);
                    }
                });
                $(".spec-real-stock").each(function (index, ele) {
                    var value = $(ele).text() || 0;
                    if (!isNaN(value)) {
                        allRealStock += parseInt(value);
                    }
                });
                $("[name=stock]").val(allStock);
                if (util.isValid('${mallGoods.id}')) {
                    $(".realStock").val(allRealStock);
                } else {
                    $(".realStock").val(allStock);
                }
            },
            // 计算成本价
            updateCostPrice: function () {
                var array = new Array();
                $(".spec-cost-price").each(function (index, ele) {
                    var value = $(ele).val() || 0;
                    if (value > 0) {
                        array.push(value);
                    }
                });
                var min = array.length > 0 && Array.min(array) ? Array.min(array) : 0;
                var max = array.length > 0 && Array.max(array) ? Array.max(array) : 0;
                if (min == max) {
                    $("[name=costPrice]").val(min);
                } else {
                    $("[name=costPrice]").val(min + '~' + max);
                }
            },
            // 计算批发价
            updateTradePrice: function () {
                var array = new Array();
                $(".spec-trade-price").each(function (index, ele) {
                    var value = $(ele).val() || 0;
                    if (value > 0) {
                        array.push(value);
                    }
                });
                var min = array.length > 0 && Array.min(array) ? Array.min(array) : 0;
                var max = array.length > 0 && Array.max(array) ? Array.max(array) : 0;
                if (min == max) {
                    $("[name=tradePrice]").val(min);
                } else {
                    $("[name=tradePrice]").val(min + '~' + max);
                }
            },
            updateNumber: function () {
                var array = new Array();
                $(".spec-number").each(function (index, ele) {
                    var value = $(ele).val() || '';
                    if (util.isValid(value)) {
                        var flag = true;
                        for (var i = 0; i < array.length; i++) {
                            if (array[i] == value) {
                                flag = false;
                            }
                        }
                        if (flag) {
                            array.push(value);
                        }
                    }
                });

                if (array.length == 1) {
                    $("[name=number]").val(array[0]);
                }
            },
            addEvent: function () {
                var that = this;
                // 添加规格
                $(".addBtn").click(function () {
                    var _giftArray = new Array();
                    $(".tag-wrap .tag-item").each(function (index, elem) {
                        var giftId = $(elem).data("id");
                        _giftArray.push(giftId);
                    });
                    var categoryId = _giftArray.join(",");
                    if (!util.isValid(categoryId)) {
                        util.layerMsgError("请先选择分类");
                        return false;
                    }
                    var specArray = [];
                    $(".spec-selected-list .rc-sku-group").each(function (index, spec) {
                        specArray[index] = $(spec).attr("data-model");
                    });
                    var requestUrl = "${ctx}/mall/spec/specDialog.do?categoryId=" + categoryId + "&specIds=" + specArray.join(",") + "&type=1";
                    layer.open({
                        type: 2,
                        area: ["400px", "300px"],
                        title: "选择分类规格",
                        maxmin: true,
                        content: requestUrl,
                        btn: ['确定', '关闭'],
                        yes: function (index, layero) {
                            var body = layer.getChildFrame('body', index);
                            var iframeWin = layero.find('iframe')[0]; //得到iframe页的窗口对象，执行iframe页的方法：iframeWin.method();
                            var inputForm = body.find('#inputForm');
                            var top_iframe;
                            top_iframe = '_parent';
                            inputForm.attr("target", top_iframe);//表单提交成功后，从服务器返回的url在当前tab中展示

                            var array = iframeWin.contentWindow.doSubmit();
                            if (array.length > 0) {
                                for (var i = 0; i < array.length; i++) {
                                    var obj = array[i];
                                    if (!specModels[obj.id]) {
                                        specModels[obj.id] = {
                                            id: obj.id,
                                            name: obj.name,
                                            subModelName: [],
                                            subModelId: [],
                                            subModelPic: [],
                                            subModelSort: []
                                        }
                                    }
                                }

                                that.getLiHtml();

                                setTimeout(function () {
                                    top.layer.close(index);
                                }, 80);
                            }
                        },
                        cancel: function (index) {
                        }
                    });
                });

                // 添加类型
                $(".spec-selected-list").delegate(".spec-item-add", "click", function (e) {
                    var $target = $(e.target);
                    var $skuGroup = $target.closest(".rc-sku-group");
                    var picChk = $skuGroup.find("[type=checkbox]").prop("checked");
                    var getTpl = $("#subItem_template").html();
                    that.myTpl(getTpl).render({picChk: picChk}, function (html) {
                        $target.before(html);
                    });
                    // $(".url-opt").hide();
                    $skuGroup.find(".sub-item:last").find("input").trigger('focus');
                });

                // 规格处理
                $(".spec-selected-list").delegate(".group-opt", "click", function (e) {
                    var $this = $(e.target);
                    var $li = $this.closest(".rc-sku-group");
                    $li.remove();

                    var picChkLength = $(".spec-selected-list").find(".rc-sku-group:eq(0)").find(".add-sub-item-pic").length;
                    if (picChkLength == 0) {
                        var getTpl = $("#picChk_template").html();
                        var $specCase = $(".spec-selected-list").find(".rc-sku-group:eq(0)").find(".spec-case");
                        that.myTpl(getTpl).render({}, function (html) {
                            $specCase.after(html);
                        });
                        that.myForm.render('checkbox');

                        that.picChk = false;
                    }

                    var modelId = $li.attr("data-model");
                    // 删除
                    delete specModels[modelId];
                    that.paintSpecificationTable();

                    var groupLength = $(".rc-sku-group").length;
                    if (groupLength == 0) { // 表示没有规格
                        that.hasSpec = false;
                        $("[name=price]").prop("readonly", false);
                        $("[name=stock]").prop("readonly", false);
                        $("[name=costPrice]").prop("readonly", false);
                        $("[name=tradePrice]").prop("readonly", false);
                        $("#myTable").closest(".layui-form-item").addClass("dn");
                    } else {
                        that.hasSpec = true;
                        $("[name=price]").prop("readonly", true);
                        $("[name=stock]").prop("readonly", true);
                        $("[name=costPrice]").prop("readonly", true);
                        $("[name=tradePrice]").prop("readonly", true);
                        $("#myTable").closest(".layui-form-item").removeClass("dn");
                    }

                    if (groupLength < 3) {
                        $(".addBtn").prop("disabled", false);
                    }
                });

                // 规格图片
                that.myForm.on('checkbox(picChk)', function (data) {
                    var $that = $(data.elem);
                    that.picChk = data.elem.checked;
                    var getTpl = $("#subItemPic_template").html();
                    $that.closest(".rc-sku-group").find(".sub-item").each(function (index, ele) {
                        $(ele).find(".upload-img-wrap").remove();
                        if (that.picChk) {
                            that.myTpl(getTpl).render(new Array(), function (html) {
                                $(ele).append(html);
                            });
                        }
                    });
                });

                // 删除规格图片
                $(".spec-selected-list").delegate(".sub-item .sub-item-pic-opt", "click", function (e) {
                    var $this = $(e.target);
                    var $wrap = $this.closest(".upload-img-wrap");
                    $wrap.find("[name=pic]").val("");
                    $wrap.find("img").attr("src", "");
                    $wrap.find("img").css("display", "none");
                    $wrap.find(".upload-icon").removeClass("upload-icon-update");
                    $wrap.find(".upload-icon").text("+");
                    that.addOrDeleteSubItem($this, true);
                });


                function renderSubOpt2($item, data) {
                    var $subItem = $item.closest(".sub-item");
                    if (data.length > 0) {
                        var _valueHtml = new Array();
                        for (var i = 0; i < data.length; i++) {
                            _valueHtml.push('<option value = "' + data[i].id + '">' + data[i].value + '</option>');
                        }
                        if (_valueHtml.length > 0) {
                            $(".spec-selected-list").find(".layui-form-select dl").hide();
                            $subItem.find(".url-opt").html(_valueHtml.join(""));
                            that.myForm.render('select');
                            $subItem.find(".layui-form-select dl").show();
                        }
                    }
                }

                function renderSubOpt($item, specId) {
                    var $subItem = $item.closest(".sub-item");
                    var data = that.specValue2[specId];
                    if (data.length > 0) {
                        var _valueHtml = new Array();
                        for (var i = 0; i < data.length; i++) {
                            var showFlag = true;
                            $item.closest(".rc-sku-group").find(".sub-item").each(function (index, ele) {
                                var value = $(ele).find(".sub-item-text input").val();
                                if (data[i].value == value) {
                                    showFlag = false;
                                    return true;
                                }
                            });
                            if (showFlag) {
                                // _valueHtml.push('<span data-id="' + data[i].id + '">' + data[i].value + '</span>');
                                _valueHtml.push('<option value = "' + data[i].id + '">' + data[i].value + '</option>');
                            }
                        }
                        if (_valueHtml.length > 0) {
                            $(".spec-selected-list").find(".layui-form-select dl").hide();
                            $subItem.find(".url-opt").html(_valueHtml.join(""));
                            that.myForm.render('select');
                            $subItem.find(".layui-form-select dl").show();
                        }
                    }
                }

                function writeSubOpt($item) {
                    var $skuGroup = $item.closest(".rc-sku-group");
                    var specId = $skuGroup.data("model");
                    var data = that.specValue2[specId];
                    $skuGroup.closest(".rc-sku-group").find(".sub-item-text input").each(function () {
                        var value = $(this).val();
                        var flag = true;
                        for (var m = 0; m < data.length; m++) {
                            if (data[m].value == value) {
                                flag = false;
                                return true;
                            }
                        }
                        if (flag && util.isValid(value)) {
                            data.push({
                                id: Math.floor(Math.random() * (999 - 99 + 1) + 99),
                                value: value
                            });
                            $item.closest(".sub-item").attr('data-id', '').attr('data-new-id', '');
                        }
                    });
                    that.specValue2[specId] = data;
                }

                that.myForm.on('select(specValue-select)', function (data) {
                    var $target = $(data.elem);
                    var specValueId = data.value;
                    var specValue = $target.find("option[value='" + specValueId + "']").text();

                    var $subItem = $target.closest(".sub-item");
                    $subItem.find(".sub-item-text").find("input").val(specValue);
                    $subItem.find(".layui-form-select dl").hide();
                    $subItem.attr('data-new-id', specValueId);
                    that.addOrDeleteSubItem($target, true);
                });

                // 根据规格获取规格值
                $(".spec-selected-list").delegate(".sub-item-text input", "focus", function (e) {
                    var specId = $(e.target).closest(".rc-sku-group").data("model");
                    var _value = that.specValue2[specId] || new Array();
                    if (!util.isValid(that.specValue[specId])) {
                        $.get("${ctx}/mall/spec/getSpecValueById.do", {"specId": specId}, function (res) {
                            if (res.success) {
                                that.specValue[specId] = true;
                                for (var i = 0; i < res.data.length; i++) {
                                    _value.push({
                                        id: res.data[i].id,
                                        value: res.data[i].value
                                    });
                                }
                                that.specValue2[specId] = _value;
                                renderSubOpt($(e.target), specId);
                            } else {
                                util.layerMsgError("获取规格值异常");
                                return false;
                            }
                        });
                    } else {
                        that.specValue2[specId] = _value;
                        renderSubOpt($(e.target), specId);
                    }
                });

                $(".spec-selected-list").delegate(".sub-item-text input", "input propertychange", function (e) {
                    var value = $(this).val();
                    console.info("正在输入" + value);
                    var $this = $(e.target);
                    var $skuGroup = $this.closest(".rc-sku-group");
                    var specId = $skuGroup.data("model");
                    var data = that.specValue2[specId];

                    function filterData(newValue) {
                        if (newValue.value.indexOf(value) != -1) {
                            return newValue;
                        }
                    }
                    renderSubOpt2($this, data.filter(filterData));
                });

                $(".spec-selected-list").delegate(".sub-item-text input", "blur", function (e) {
                    var $this = $(e.target);
                    that.hasSpec = true;

                    var _value = new Array();
                    var _flag = true;
                    $this.closest(".rc-sku-group").find(".sub-item .sub-item-text input").each(function () {
                        var value = $(this).val();
                        if (util.isValid(value)) {
                            for (var m = 0; m < _value.length; m++) {
                                if (_value[m] == value) {
                                    $this.val("");
                                    util.layerMsgError("已经添加了相同的规格值")
                                    _flag = false;
                                    return _flag;
                                }
                            }
                            _value.push(value);
                        }
                    });
                    if (_flag) {
                        setTimeout(function () {
                            $this.closest(".sub-item").find(".layui-form-select dl").hide();
                        }, 1000);
                        writeSubOpt($this);
                        that.addOrDeleteSubItem($this, true);
                    }
                    e.stopPropagation();
                });

                // 删除规格值
                $(".spec-selected-list").delegate(".sub-item .sub-item-opt", "click", function (e) {
                    var $this = $(e.target);
                    $this.closest(".sub-item").addClass("dn");
                    $this.closest(".sub-item").find("input").val("");
                    that.addOrDeleteSubItem($this, true);
                    $this.closest(".sub-item").remove();
                    var $wrap = $this.closest(".upload-img-wrap");
                    $wrap.find("img").attr("src", "");
                    $wrap.find("img").css("display", "none");
                    $wrap.remove();
                    $this.closest(".sub-item").remove();
                });

                function checkPrice(value, obj) {
                    if (!util.checkFloat(value) || parseFloat(value) == 0) {
                        util.layerMsgError("请输入一个正确的价格");
                        // $(obj).val("");
                        return false;
                    }
                    return true;
                }

                function checkStock(value, obj) {
                    if (!util.checkNumber(value)) {
                        util.layerMsgError("请输入一个正确的库存");
                        // $(obj).val("");
                        return false;
                    }
                    return true;
                }

                $("#myTable").delegate("td input", "input", function (e) {
                    var $this = $(e.target);
                    var value = $(this).val();
                    var key = $this.closest('tr[data-models]').attr('data-models');
                    if ($this.hasClass("spec-all-price")) { // 设置统一价格
                        if (checkPrice(value, $this)) {
                            $(".spec-price").val(value).trigger('input');
                            that.updatePrice(value);
                        }
                    } else if ($this.hasClass("spec-all-stock")) { // 设置统一库存
                        if (checkStock(value, $this)) {
                            $(".spec-stock").val(value).trigger('input');
                            that.updateStock();
                        }
                    } else if ($this.hasClass("spec-price")) { // 单个价格
                        if (checkPrice(value, $this)) {
                            subPriceStock[key] = subPriceStock[key] || {};
                            subPriceStock[key].price = value;
                            that.updatePrice();
                        }
                    } else if ($this.hasClass("spec-stock")) { // 单个库存
                        if (checkStock(value, $this)) {
                            var $realStock = $this.closest("tr").find(".spec-real-stock");
                            var productId = $this.closest("tr").attr("data-productId");
                            var stock = parseInt(value || 0);
                            if (stock == 0) {
                                $realStock.text(0);
                            } else {
                                if (!util.isValid(productId)) { // 表示新增
                                    $realStock.text(stock);
                                }
                                var salesNum = $this.closest("tr").find(".spec-salesNum").val() || 0; // 销量
                                var notPayCount = $(this).closest("tr").find("[name=notPayCount]").val() || 0; // 未付款数
                                var realStock = stock - parseInt(salesNum) - parseInt(notPayCount);
                                if (realStock < 0) {
                                    realStock = 0;
                                }
                                $realStock.text(realStock);
                            }

                            // 单个库存
                            subPriceStock[key] = subPriceStock[key] || {};
                            subPriceStock[key].stock = value;
                            subPriceStock[key].realStock = $realStock.text();

                            that.updateStock();
                        }
                    } else if ($this.hasClass("spec-all-cost-price")) { // 统一成本价
                        if (checkPrice(value, $this)) {
                            $(".spec-cost-price").val(value).trigger('input');
                            that.updateCostPrice();
                        }
                    } else if ($this.hasClass("spec-all-trade-price")) { // 统一批发价
                        if (checkPrice(value, $this)) {
                            $(".spec-trade-price").val(value).trigger('input');
                        }
                    } else if ($this.hasClass("spec-cost-price")) { // 单个成本价
                        if (checkPrice(value, $this)) {
                            subPriceStock[key] = subPriceStock[key] || {};
                            subPriceStock[key].costPrice = value;
                            that.updateCostPrice();
                        }
                    } else if ($this.hasClass("spec-trade-price")) { // 单个批发价
                        if (checkPrice(value, $this)) {
                            var price = $this.closest("tr").find(".spec-price").val();
                            if (parseFloat(value) >= parseFloat(price)) {
                                util.layerMsgError("批发价不能大于等于售价，请重新设置");
                                $this.addClass('red');
                                return false;
                            } else {
                                $this.removeClass('red');
                            }

                            subPriceStock[key] = subPriceStock[key] || {};
                            subPriceStock[key].tradePrice = value;
                            that.updateTradePrice();
                        }
                    } else if ($this.hasClass("spec-all-number")) { // 统一规格编码
                        if (util.isValid(value)) {
                            $(".spec-number").val(value).trigger('input');
                        }
                    } else if ($this.hasClass("spec-number")) { // 单个规格编码
                        if (util.isValid(value)) {
                            subPriceStock[key] = subPriceStock[key] || {};
                            subPriceStock[key].number = value;
                            that.updateNumber();
                        }
                    }
                });

                $("tbody tr").delegate(".delete", "click", function (e) {
                    var $tr = $(e.target).closest("tr");
                    var productId = $tr.attr("data-productId");
                    var length = $("tbody tr").length;
                    if (length == 1) {
                        util.layerMsgError("只有一个产品不能删除！");
                        return false;
                    }
                    txz.deleteObject("确定要删除该产品？", "${ctx}/mall/goods/deleteProduct.do?productId=" + productId)
                });
            },
            getLiHtml: function () {
                var that = this;
                var content = $(".sku-container");
                $(content).html("");
                var getTpl = $("#sku_template").html();
                that.myTpl(getTpl).render(specModels, function (html) {
                    content.append(html);
                });
                that.myForm.render('checkbox');
                that.myForm.render('select');
                var chkLength = $(content).find("[type=checkbox]:checked").length;
                if (chkLength > 0) {
                    that.picChk = true;
                }
                var skuLength = $(".rc-sku-group").length;
                if (skuLength >= 3) {
                    $(".addBtn").prop("disabled", true);
                }
            },
            // 拼接tbody内容
            getTableHtml: function (array) {
                var html = new Array();
                if (!array || !array.length) {
                    return html.join("");
                }
                $.each(array, function (i, data) {
                    html.push('<tr class="tr-data" data-models=' + data.id.toString() + '>');
                    $.each(data.specValue, function (index, name) {
                        var rowspan = data.rowspan[index];
                        var pic = data.pic[index];
                        if (util.isValid(pic)) {
                            html.push('<input class="spec-value-pic" data-specId=' + data.specId[index] + ' type="hidden" name="prodPic" value="' + pic + '" />');
                        }

                        html.push('<input type="hidden" class="spec-value"  data-model = "' + data.id[index] + '" ' +
                            'value = "' + name + '" data-specId = "' + data.specId[index] + '" ' +
                            'data-spec-sort = "' + data.specSort[index] + '"' +
                            'data-spec-value-sort = "' + data.specValueSort[index] + '" />');
                        if (rowspan > 0) {
                            html.push('<td rowspan="' + rowspan + '"><div>' + name + '</div></td>');
                        }
                    });
                    html.push('</tr>');
                });
                return html.join("");
            },
            removeDelete: function (tableData) {
                for (var i = 0; i < delModelList.length; i++) {
                    var value = delModelList[i];
                    for (var j = 0; j < tableData.length; j++) {
                        var value2 = tableData[j].id;
                        var flag = "";
                        $.each(value2, function (kkk, vvv) {
                            $.each(value.split(","), function (kk, vv) {
                                if (vv == vvv) {
                                    flag += "true,";
                                } else {
                                    flag += "false,";
                                }
                            });
                        });
                        if (flag != "") {
                            flag = flag.substring(0, flag.length - 1);
                        }
                        var trueArray = flag.split(",").filter(function (ff) {
                            return ff == "true";
                        });
                        if (trueArray.length == value.split(",").length) {
                            tableData.splice(j, 1);
                            j = j - 1;
                        }
                    }
                }
            },
            submitBefore: function () {
                $("#hiddenForm").html("");
                var array = [];
                var flag = true;
                var that = this;
                if (that.hasSpec == true) {

                    var specArray = new Array();
                    $(".rc-sku-group").each(function (i, ele) {
                        var specId = $(ele).attr("data-model");
                        var picChk = $(ele).find("[type=checkbox]").prop("checked");

                        $(ele).find(".sub-item").each(function (j, subItem) {
                            var id = $(subItem).attr("data-new-id") || '';
                            var specValue = $(subItem).find("input").val();
                            var pic = $(subItem).find("[name=pic]").val() || '';

                            if (picChk && !util.isValid(pic)) {
                                util.layerMsgError("请上传规格值图片");
                                flag = false;
                                return flag;
                            }

                            specArray.push('<input type="hidden" name="specs[' + i + '].specValues[' + j + '].id" value="' + id + '" />');
                            specArray.push('<input type="hidden" name="specs[' + i + '].specValues[' + j + '].specId" value="' + specId + '" />');
                            specArray.push('<input type="hidden" name="specs[' + i + '].specValues[' + j + '].value" value="' + specValue + '" />');
                        });
                        if (!flag) {
                            return flag;
                        }
                    });

                    if (!flag) {

                    } else {
                        if ($(".spec-selected-list .group-title").length == 0) {
                            util.layerMsgError("请选择商品规格");
                            flag = false;
                            return flag;
                        } else if ($("#myTable tbody").find(".tr-data").length == 0) {
                            util.layerMsgError("请输入商品规格值");
                            flag = false;
                            return flag;
                        }

                        $("#myTable tbody").find(".tr-data").each(function (i, tr) {
                            var $specValuePic = $(tr).find(".spec-value-pic");
                            var specPic_specId = $specValuePic.attr('data-specId');

                            var productId = $(tr).attr("data-productId");
                            var pic = $specValuePic.val() || '';
                            var price = $(tr).find(".spec-price").val();
                            var stock = $(tr).find(".spec-stock").val();
                            var costPrice = $(tr).find(".spec-cost-price").val();
                            var tradePrice = $(tr).find(".spec-trade-price").val();
                            var number = $(tr).find(".spec-number").val();
                            var realStock = $(tr).find(".spec-real-stock").text() || stock;

                            if (!util.isValid(price)) {
                                util.layerMsgError("请输入价格");
                                flag = false;
                                return flag;
                            } else if (!util.checkPrice(price)) {
                                util.layerMsgError("价格格式错误");
                                flag = false;
                                return flag;
                            }

                            if (!util.isValid(stock)) {
                                util.layerMsgError("请输入库存");
                                flag = false;
                                return flag;
                            } else if (!util.checkNumber(stock)) {
                                util.layerMsgError("库存数只能为整数");
                                flag = false;
                                return flag;
                            } else if (stock < parseInt(realStock)) {
                                util.layerMsgError("总库存不能小于实际库存");
                                flag = false;
                                return flag;
                            }

                            if (!util.isValid(costPrice)) {
                                util.layerMsgError("请输入成本价");
                                flag = false;
                                return flag;
                            } else if (!util.checkPrice(costPrice)) {
                                util.layerMsgError("成本价格式错误");
                                flag = false;
                                return flag;
                            }

                            if (!util.isValid(tradePrice)) {
                                util.layerMsgError("请输入批发价");
                                flag = false;
                                return flag;
                            } else if (!util.checkPrice(tradePrice)) {
                                util.layerMsgError("批发价格式错误");
                                flag = false;
                                return flag;
                            }
                            if (parseFloat(tradePrice) >= parseFloat(price)) {
                                $(tr).find(".spec-trade-price").addClass('red');
                                util.layerMsgError("批发价不能大于等于售价，请重新设置");
                                flag = false;
                                return flag;
                            }


                            // array.push('<input type="hidden" name="products[' + i + '].sort" value="' + (i + 1) + '"/>');
                            array.push('<input type="hidden" name="products[' + i + '].id" value="' + productId + '"/>');
                            array.push('<input type="hidden" name="products[' + i + '].pic" value="' + pic + '" />');
                            array.push('<input type="hidden" name="products[' + i + '].price" value="' + price + '" />');
                            array.push('<input type="hidden" name="products[' + i + '].stock" value="' + stock + '" />');
                            array.push('<input type="hidden" name="products[' + i + '].costPrice" value="' + costPrice + '" />');
                            array.push('<input type="hidden" name="products[' + i + '].tradePrice" value="' + tradePrice + '" />');
                            array.push('<input type="hidden" name="products[' + i + '].number" value="' + number + '" />');

                            $(tr).find(".spec-value").each(function (k, td) {
                                var specValueId = $(td).attr('data-model');
                                var specId = $(td).attr("data-specId");
                                var specValueSort = $(td).attr("data-spec-value-sort");
                                var specSort = $(td).attr('data-spec-sort');
                                var specValue = $(td).val();
                                array.push('<input type="hidden" name="products[' + i + '].specs[' + k + '].specSort" value="' + specSort + '" />');
                                array.push('<input type="hidden" name="products[' + i + '].specs[' + k + '].specValueSort" value="' + specValueSort + '" />');
                                array.push('<input type="hidden" name="products[' + i + '].specs[' + k + '].specId" value="' + specId + '" />');
                                array.push('<input type="hidden" name="products[' + i + '].specs[' + k + '].specValue" value="' + specValue + '" />');
                                array.push('<input type="hidden" name="products[' + i + '].specs[' + k + '].specValueId" value="' + specValueId + '" />');

                                var picFlag = 1;
                                if (specId != specPic_specId) {
                                    pic = '';
                                    picFlag = 0;
                                }
                                array.push('<input type="hidden" name="products[' + i + '].specs[' + k + '].specPicFlag" value="' + picFlag + '" />');
                                array.push('<input type="hidden" name="products[' + i + '].specs[' + k + '].specValuePic" value="' + pic + '" />');
                            });
                        });

                        $("#hiddenForm").append(specArray.join(""));
                    }
                } else {
                    if (util.isValid(that.productId)) {
                        array.push('<input type="hidden" name="products[0].id" value="' + that.productId + '"/>');
                    }
                }
                if (flag) {
                    $("#hiddenForm").append(array.join(""));
                }
                return flag;
            },
            // 修改商品规格详情表格
            paintSpecificationTable: function () {
                var that = this;
                var head = '', body = '', cases = '', label = '', name = '', headArray = new Array();
                var bodyFragment = $(document.createDocumentFragment());
                var subModelNameArr = [];
                var tableData = [];

                $.each(specModels, function (key, model) {
                    if (model.subModelId.length) {
                        head += '<td>' + model.name + '</td>';
                        subModelNameArr.push((function (arr) {
                            $.each(model.subModelId, function (index, id) {
                                arr.push({
                                    id: id,
                                    specValue: model.subModelName[index],
                                    specId: model.id,
                                    specSort: model.sort,
                                    pic: model.subModelPic[index],
                                    specValueSort : model.subModelSort[index]
                                });
                            });
                            return arr;
                        })([]));
                    }
                });
                subModelNameArr[0] && $.each(subModelNameArr[0], function (i, model1) {
                    if (!subModelNameArr[1]) {
                        tableData.push({
                            id: [model1.id],
                            specValue: [model1.specValue],
                            specId: [model1.specId],
                            specValueSort: [model1.specValueSort],
                            specSort : [model1.specSort],
                            rowspan: [1],
                            pic: [model1.pic]
                        });
                    } else {
                        $.each(subModelNameArr[1], function (j, model2) {
                            if (!subModelNameArr[2]) {
                                var rowspan = j == 0 ? 1 * subModelNameArr[1].length : 0;
                                tableData.push({
                                    id: [model1.id, model2.id],
                                    specValue: [model1.specValue, model2.specValue],
                                    specId: [model1.specId, model2.specId],
                                    specValueSort: [model1.specValueSort, model2.specValueSort],
                                    specSort : [model1.specSort, model2.specSort],
                                    rowspan: [rowspan, 1],
                                    pic: [model1.pic, model2.pic]
                                });
                            } else {
                                $.each(subModelNameArr[2], function (k, model3) {
                                    var rowspan1 = (j == 0 && k == 0) ? subModelNameArr[2].length * subModelNameArr[1].length : 0;
                                    var rowspan2 = k == 0 ? 1 * subModelNameArr[2].length : 0;
                                    tableData.push({
                                        id: [model1.id, model2.id, model3.id],
                                        specValue: [model1.specValue, model2.specValue, model3.specValue],
                                        specId: [model1.specId, model2.specId, model3.specId],
                                        specValueSort: [model1.specValueSort, model2.specValueSort, model3.specValueSort],
                                        specSort : [model1.specSort, model2.specSort, model3.specSort],
                                        rowspan: [rowspan1, rowspan2, 1],
                                        pic: [model1.pic, model2.pic, model3.pic]
                                    });
                                });
                            }
                        });
                    }
                });
                this.removeDelete(tableData);
                body = this.getTableHtml(tableData);
                if (body) {
                    headArray.push('<thead><tr>' + head);
                    // headArray.push('<td>图片</td>');
                    headArray.push('<td><span><b class="t-verify-red">*</b>价格</span></td>');
                    headArray.push('<td><span><b class="t-verify-red">*</b>总库存</span></td>');
                    if (util.isValid('${mallGoods.id}')) {
                        headArray.push('<td class="w-50px">剩余库存</td>');
                        // headArray.push('<td style="width: 50px">操作</td>');
                    }
                    headArray.push('<td class="w-90px">规格编码</td>');
                    headArray.push('<td class="w-70px"><b class="t-verify-red">*</b>成本价</td>');
                    headArray.push('<td class="w-70px"><b class="t-verify-red">*</b>批发价</td>');
                    headArray.push('<td class="w-50px">销量</td>');
                    body = '<tbody>' + body + '</tbody>';
                    bodyFragment.append(body).find('tbody > tr').each(function (index, row) {
                        var key = $(row).attr('data-models');
                        var newArray = key.split(",");
                        var price = '', stock = '', imgurl = '', body_goods = '', productId = '', realStock = '',
                            salesNum = '0', notPayCount = 0, costPrice = '', tradePrice = '', number  = '';

                        $.each(subPriceStock, function (key, value) {
                            var flag = "";
                            $.each(newArray, function (key2, value2) {
                                if (key.indexOf(value2) != -1) {
                                    flag += true;
                                } else {
                                    flag += false;
                                }
                            })

                            if (flag.indexOf("false") == -1) {
                                price = util.isValid(value.price) ? value.price : '';
                                stock = util.isValid(value.stock) ? value.stock : '';
                                salesNum = util.isValid(value.salesNum) ? value.salesNum : 0;
                                costPrice = util.isValid(value.costPrice) ? value.costPrice : '';
                                tradePrice = util.isValid(value.tradePrice) ? value.tradePrice : '';
                                number = util.isValid(value.number) ? value.number : '';


                                if (util.isValid(value.realStock)) {
                                    realStock = value.realStock;
                                } else if (util.isValid(stock) && !util.isValid(realStock)) {
                                    realStock = stock - salesNum;
                                } else {
                                    realStock = '';
                                }

                                if (util.isValid(stock) && util.isValid(realStock)) {
                                    if (realStock > stock) {
                                        notPayCount = 0;
                                    } else {
                                        notPayCount = stock - realStock - salesNum;
                                    }
                                }

                                imgurl = util.isValid(value.imgUrl) ? value.imgUrl : '';
                                productId = util.isValid(value.productId) ? value.productId : '';
                                return;
                            }
                        });
                        /*body_goods = '<td><div>' +
                            '<img src="' + imgurl + '" class="spec-img" alt=""/>' +
                            '<input type="hidden" name="prodPic" value="' + imgurl + '" />' +
                            '<a class="layui-btn layui-btn-danger sel-single-img">更换</a>' +
                            '</div></td>';*/

                        body_goods += '<td>' +
                            '<input type="number" min="1" class="layui-input spec-price" value="' + price + '"/>' +
                            /*'<input type="hidden" name="prodPic" value="' + imgurl + '" />' +*/
                            '<input type="hidden" name="notPayCount" value="' + notPayCount + '" />' +
                            '</td>';
                        body_goods += '<td><input type="text" class="layui-input spec-stock" value="' + stock + '"/></td>';
                        if (util.isValid('${mallGoods.id}')) {
                            body_goods += '<td><div class="spec-real-stock">'+ realStock +'</div></td>';
                            // body_goods += '<td><a href="javascript:void(0);" class="red delete">刪除</a></td>';
                        }
                        body_goods += '<td><input type="text" class="layui-input spec-number" value="' + number + '" /></td>';
                        body_goods += '<td><input type="number" min="1" class="layui-input spec-cost-price" value="' + costPrice + '" /></td>';
                        body_goods += '<td><input type="number" min="1" class="layui-input spec-trade-price" value="' + tradePrice + '" /></td>';
                        body_goods += '<td><div class="spec-salesNum">'+ salesNum +'</div></td>';
                        $(row).attr("data-productId", productId);
                        $(row).append(body_goods);
                    });
                    $('#myTable').html(headArray.join("")).append(bodyFragment);

                    var rowspanLength = $("#myTable tbody").find(".tr-data:eq(0)").find("td").length;
                    var getTpl = $("#batchOpt_template").html();
                    that.myTpl(getTpl).render({
                        rowspanLength: rowspanLength
                    }, function (html) {
                        $('#myTable').append(html);
                    });
                } else {
                    $('#myTable').html('');
                }

                if (that.hasSpec) {
                    that.updatePrice();
                    that.updateStock();
                    that.updateCostPrice();
                    that.updateTradePrice();
                    that.updateNumber();
                }

                that.buildTableUpload();
                // that.buildSkuUpload();
            }
        }
    });
</script>
